package seatiger.tomcat.catalina.session;

import seatiger.tomcat.catalina.Container;
import seatiger.tomcat.catalina.Manager;
import seatiger.tomcat.catalina.Session;

import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Session管理器的基础实现
 */
public abstract class ManagerBase implements Manager {
    /**
     * 关联容器
     */
    private Container container;

    /**
     * 当前有效的session对象
     */
    private Map<String,Session> sessions = new ConcurrentHashMap<>();

    /**
     * session 的过期时间
     */
    protected int maxInactiveInterval = 10 * 60;

    @Override
    public Container getContainer() {
        return this.container;
    }

    @Override
    public void setContainer(Container container) {
        this.container = container;
    }

    @Override
    public void add(Session session) {
        sessions.put(session.getId(),session);
    }

    @Override
    public Session createSession() {
        Session session = createEmptySession();
        session.setId(UUID.randomUUID().toString());
        session.setValid(true);
        session.setMaxInactiveInterval(this.maxInactiveInterval);
        return session;
    }

    @Override
    public Session createEmptySession() {
        return new StandardSession(this);
    }

    @Override
    public Session findSession(String id) throws IOException {
        return id == null ? null : sessions.get(id);
    }

    @Override
    public void remove(Session session) {
        sessions.remove(session.getId());
    }

    @Override
    public Session[] findSessions(){
        return sessions.values().toArray(new Session[0]);
    }


}
